import { message } from 'antd';
import { timestampMeta, startLoading } from './reducerUtil';

/** 异步Action */
export const asyncAction = ({ type, payload, handlers, meta }) => (dispatch) => {
  dispatch(startLoading(type));
  dispatch({
    type,
    payload,
    // 调用timestampMeta，支持处理同一个请求的先后顺序问题
    meta: timestampMeta({ handlers, ...meta }),
  });
};

/** 异步Action Handlers */
export const asyncActionHandler = (actions, successBack, failedBack, finallyBack) => ({
  success: (dispatch) => {
    message.success('操作成功');
    actions && dispatch(actions);
    successBack && successBack();
  },
  failed: (dispatch, getState, error = {}) => {
    failedBack && failedBack();
    message.error(error.message || '操作失败');
  },
  finally: () => {
    finallyBack && finallyBack();
  }
});
